const API_BASE = import.meta.env.VITE_API_BASE || '/api'


export async function getSessions(userId) {
  const res = await fetch(`${API_BASE}/ai/sessions?userId=${userId}`)
  return res.json()
}

export async function getMessages(sessionId) {
  const res = await fetch(`${API_BASE}/ai/messages?sessionId=${sessionId}`)
  return res.json()
}

export async function createSession(userId, title = '新会话') {
  const res = await fetch(`${API_BASE}/ai/sessions`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ userId, title })
  })
  return res.json()
}

export async function deleteSession(sessionId) {
  await fetch(`${API_BASE}/ai/sessions/${sessionId}`, { method: 'DELETE' })
}

export async function sendChat(userId, sessionId, prompt) {
  const res = await fetch(`${API_BASE}/ai/chat`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ userId, sessionId, prompt })
  })
  return res.json()
}

// SSE连接方法
export function connectSSE(userId) {
  if (window.eventSource) {
    window.eventSource.close()
  }
  
  window.eventSource = new EventSource(`${API_BASE}/sse/connect?userId=${userId}`)
  return window.eventSource
}

// 流式聊天方法
export async function sendStreamChat(userId, message, sessionId) {
  await fetch(`${API_BASE}/chat/ai`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      currentUserName: String(userId), // 使用userId作为SSE连接的唯一标识
      message: message,
      userId: userId,
      sessionId: sessionId,
    }),
  })
}

// Dify 工作流：上传文件
export async function difyUpload(file, user, { sessionId, userId } = {}) {
  const form = new FormData()
  form.append('file', file)
  if (sessionId != null) form.append('sessionId', String(sessionId))
  if (userId != null) form.append('userId', String(userId))
  const qs = user ? `?user=${encodeURIComponent(user)}` : ''
  const res = await fetch(`${API_BASE}/dify/upload${qs}`, {
    method: 'POST',
    body: form
  })
  const text = await res.text()
  try { return JSON.parse(text) } catch { return { raw: text } }
}

// Dify 工作流：执行
export async function difyRun(payload) {
  const res = await fetch(`${API_BASE}/dify/workflows/run`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  })
  return res.json()
}